<template>
	<view>
		<!-- 操作按钮 -->
		<el-row>
			<el-col :span="1.5" style="margin-right: 10rpx"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button></el-col>
			<!--      <el-col :span="1.5">-->
			<!-- <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除 -->
			<!--        </el-button>-->
			<!--      </el-col>-->
		</el-row>

		<!-- 数据展示 -->
		<el-table v-loading="loading" :data="projects" stripe @selection-change="handleSelectionChange" class="table_content">
			<!-- <el-table-column type="selection"></el-table-column> -->
			<el-table-column align="center" prop="name" label="志愿名称"></el-table-column>
			<el-table-column align="center" prop="type" label="志愿类型" />
			<el-table-column align="center" prop="author" label="发起人">
				<template slot-scope="scope">
					<view>{{ scope.row.author }}</view>
				</template>
			</el-table-column>
			<el-table-column align="center" prop="member" show-overflow-tooltip label="参与者">
				<template slot-scope="scope">
					<view v-if="scope.row.member.length > 0">{{ scope.row.member[0].username + (scope.row.member.length > 1 ? '...' : '') }}</view>
				</template>
			</el-table-column>
			<el-table-column align="center" prop="gallery" label="活动相册">
				<template slot-scope="scope">
					<scroll-view scroll-x>
						<view class="table_content-gallery">
							<image class="table_content-img" :src="i.img" mode="aspectFit" v-for="(i, idx) in scope.row.gallery" :key="idx + Math.random()"></image>
						</view>
					</scroll-view>
				</template>
			</el-table-column>
			<el-table-column align="center" show-overflow-tooltip prop="desc" label="说明">
				<template slot-scope="scope">
					<view>{{ scope.row.desc }}</view>
				</template>
			</el-table-column>
			<el-table-column fixed="right">
				<view class="uni-group" slot-scope="scope">
					<button
						class="uni-button"
						size="mini"
						type="primary"
						@click="
							() => {
								signinShow = true;
								signin.activity_id = scope.row._id;
							}
						"
					>
						签到
					</button>
					<button class="uni-button" size="mini" type="primary" @click="handleUpdate(scope.row)">修改</button>
					<button class="uni-button" size="mini" type="warn" @click="handleDelete(scope.row)">删除</button>
				</view>
			</el-table-column>
		</el-table>

		<!-- 志愿修改 -->
		<el-dialog class="dialog" :title="dialogTitle" :visible.sync="dialogShow" width="600px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="志愿名称" prop="name"><el-input v-model="form.name" placeholder="请输入志愿活动名称" /></el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="志愿类型" prop="type">
							<el-select v-model="form.type" placeholder="请选择类型" @change="changeProjectType">
								<el-option v-for="item in projectType" :key="item._id + Math.random()" :value="item.type_name"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="发起人" prop="author">{{ form.author }}</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="dialogTitle === '修改志愿项目'">
					<el-col :span="12">
						<el-form-item label="参与者" prop="member">
							<view class="members">
								<view v-for="(m, idx) in form.member" :key="m._id" class="members-item" @click="handleDeleteMember(idx)">{{ m.username || m[0].username }}</view>
							</view>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="活动图片" prop="gallery">
							<view class="gallery">
								<image
									class="gallery-img"
									v-for="(item, index) in form.gallery"
									:key="index"
									:src="item.img"
									mode="aspectFill"
									@click="handleDeleteImg(form.gallery, index)"
								></image>
								<view class="gallery-img gallery-upload" @click="handleUploadImg(form.gallery)"><i class="el-icon-plus"></i></view>
							</view>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="志愿介绍" class="dialog_edit">
							<textarea style="box-shadow: 0 1px 1px rgba(27,31,35,0.2);padding: 10rpx" v-model="form.desc"></textarea>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="danger" @click="quit">退出</el-button>
				<el-button type="primary" @click="submit">确定</el-button>
			</div>
		</el-dialog>

		<!-- 签到 -->
		<el-dialog class="dialog" title="签到" :visible.sync="signinShow" width="600px" append-to-body>
			<el-row :gutter="10">
				<el-col :span="4">地点</el-col>
				<el-col :span="8"><el-input v-model="signin.area" placeholder="活动地点" /></el-col>
			</el-row>
			<el-row :gutter="10">
				<el-col :span="4">活动记录</el-col>
				<el-col :span="8">
					<view class="gallery">
						<image
							class="gallery-img"
							v-for="(item, index) in signin.photos"
							:key="index"
							:src="item.img"
							mode="aspectFill"
							@click="handleDeleteImg(signin.photos, index)"
						></image>
						<view class="gallery-img gallery-upload" @click="handleUploadImg(signin.photos)"><i class="el-icon-plus"></i></view>
					</view>
				</el-col>
			</el-row>
			<el-row type="flex" justify="end"><el-button type="primary" @click="handleSignin">签到</el-button></el-row>
		</el-dialog>
	</view>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import { getActivity, getTypeList } from '../../../api/project';

const db = uniCloud.database();

export default {
	data() {
		return {
			projects: [],
			dialogShow: false,
			dialogTitle: '',
			form: {},
			rules: {},
			ids: [],
			multiple: true,
			loading: false,
			users: [],
			currentUser: null,
			uploadImageUrl: null,
			projectType: [],
			projectTypeIndex: 0,
			isAdd: false,
			signinShow: false,
			signin: {
				activity_id: null,
				user_id: null,
				area: null,
				time: null,
				photos: []
			}
		};
	},
	filters: {
		descFilter(val) {
			let s = val;
			if (val.length > 12) s = s.substring(0, 10) + '...';
			return s;
		}
	},
	created: function() {
		this.getTypeList();
		this.getList();
	},
	methods: {
		getList() {
			let that = this;
			that.loading = true;
			let d = that.userInfo.username === 'admin' ? '' : that.userInfo._id
			// 获取活动列表
			that.$request('system/project/list', d).then(res => {
				that.projects = res.data;
				console.log(res)
			});
			that.loading = false;
		},
		getTypeList() {
			let that = this;
			getTypeList().then(res => {
				that.projectType = res.result.data;
			});
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		handleAdd() {
			this.reset();
			this.form.author.push(this.userInfo);
			this.dialogTitle = '添加志愿项目';
			this.dialogShow = true;
			this.isAdd = true;
		},
		handleDelete(row) {
			let that = this
			if (that.userInfo._id !== row.author._id) {
			  that.msgError('普通成员不能删除活动');
			  return
			}
			const projectId = row._id || that.ids;
			that.$confirm('是否确认删除名称为"' + row.name + '"的活动?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				that.$request('system/project/remove', { projectId, user_id: that.userInfo._id })
					.then(res => {
						if (res.result === '你不能删除此活动') {
							that.msgError('普通成员不能删除活动');
							return;
						}
						that.getList();
						that.msgSuccess('删除成功');
					})
					.catch(e => {
						console.log(e);
					});
			});
		},
		reset() {
			this.form = {
				id: undefined,
				name: '',
				author: [],
				member: [],
				gallery: [],
				desc: ''
			};
		},
		submit() {
			if (this.isAdd) {
				this.form.member.push(this.form.author[0]);
				this.$request('system/project/add', this.form).then(res => {
					this.getList();
					this.msgSuccess('添加成功');
				});
			} else {
				this.$request('system/project/update', this.form).then(res => {
					this.getList();
					this.msgSuccess('修改成功');
				});
			}
			this.dialogShow = false;
		},
		quit() {
			let that = this
			that.dialogShow = false
			that.$confirm('确认退出此活动？', '', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				that.$request('system/project/quit', {
					user_id: that.userInfo._id,
					activity_id: that.form._id
				}).then(res => {
					console.log(res);
					that.msgSuccess('退出成功');
					that.getList();
					that.reset();
				})
			});
		},
		cancel() {
			this.dialogShow = false;
			this.reset();
		},
		handleUpdate(row) {
			this.reset();
			// this.$request('system/project/selectById', row._id).then(res => {
			// 	console.log(res)
			// 	this.form = res.data[0];
			// });
			this.form = row
			this.dialogTitle = '修改志愿项目';
			this.dialogShow = true;
			this.isAdd = false;
		},
		remoteMethod() {
			console.log('remoteMethod');
		},
		handleSelectMember() {
			this.currentUser && this.form.member.push(this.currentUser);
			this.currentUser = null;
		},
		handleDeleteMember(index) {
			console.log('删除用户 ' + this.form.member[index]);
			// this.form.member.splice(index, 1)
		},
		handleDeleteImg(goal, index) {
			goal.length > index && goal.splice(index, 1);
		},
		uploadImgSuccess() {
			this.$message.success('上传成功');
		},
		beforeImgUpload(file) {
			const isJPG = file.type === 'image/jpeg';
			const isLt2M = file.size / 1024 / 1024 < 2;
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!');
			}
			return isLt2M;
		},
		handleUpload(e) {
			console.log(e);
		},
		handleUploadImg(goal) {
			let that = this;
			uni.chooseImage({
				count: 1,
				async success(res) {
					if (res.tempFilePaths.length > 0) {
						let filePath = res.tempFilePaths[0];
						await uniCloud
							.uploadFile({
								filePath: filePath,
								cloudPath: that.form.id + '/' + res.tempFiles[0].name,
								onUploadProgress: function(progressEvent) {
									var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
								}
							})
							.then(res => {
								let o = { img: res.fileID };
								goal && goal.push(o);
							});
					}
				}
			});
		},
		changeProjectType(e) {
			// this.projectTypeIndex = e.detail.value;
			// this.form.type = this.projectType[this.projectTypeIndex].value
			console.log(e);
		},
		typeFormat(row, col, cell, index) {
			for (const projectTypeElement of this.projectType) {
				if (projectTypeElement.value === cell) return projectTypeElement.type;
			}
			return cell;
		},
		handleSignin() {
			let that = this;
			that.signin.user_id = that.userInfo._id;
			that.$request('system/project/signin', that.signin).then(res => {
				that.$message.success('签到成功');
				that.signin = {
					activity_id: null,
					user_id: null,
					area: null,
					time: null,
					photos: []
				};
				that.signinShow = false;
			});
		}
	},
	computed: {
		...mapState('user', ['userInfo'])
	}
};
</script>

<style lang="scss">
$gallery_img_size: 300rpx;

.table_content {
	&-gallery {
		width: 100%;
		height: 100rpx;
		overflow: hidden;
	}

	&-img {
		width: 100%;
		height: 100rpx;
		object-fit: contain;
		display: inline-block;
		margin-left: 10rpx;
		cursor: pointer;
	}
}

.dialog {
	.members {
		&_add {
			cursor: pointer;
			font-size: 2em;

			&:hover {
				color: #3a8ee6;
			}
		}

		&_select {
			display: flex;
			align-items: center;
		}

		&-item {
			padding: 0 10rpx;
			border: 1px solid #cccccc;
			margin: 0 0 10rpx 20rpx;
			border-radius: 10rpx;
			cursor: pointer;
			display: inline-block;

			&:hover {
				background-color: rgba(0, 0, 0, 0.1);
			}
		}
	}

	.gallery {
		display: grid;
		grid-template-columns: repeat(3, $gallery_img_size);
		grid-gap: 20rpx;

		&-img {
			cursor: pointer;
			width: $gallery_img_size;
			height: 0.75 * $gallery_img_size;
			border-radius: 10rpx;
		}

		&-upload {
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2px dashed #3a8ee6;
			font-size: 3em;
			color: #3a8ee6;
		}
	}

	&_edit {
		width: 3 * $gallery_img_size + 80rpx + 80rpx;
	}
}
</style>
